#include <boost/bind.hpp>

#include "net_socket.h"
#include "net_app.h"

NetApp::NetApp(void) : m_thread(NULL)
{
}

NetApp::~NetApp(void)
{
}

bool NetApp::Run()
{
	if (m_thread)
	{
		LOG_WARN("%s, thread is running", __FUNCTION__);
		return false;
	}

	m_thread = new boost::thread(
		boost::bind(&NetApp::RunProc, this));

	return true;
}

void NetApp::Stop()
{
	m_io_service.stop();

	if(m_thread)
	{
		m_thread->join();
		SAFE_DELETE(m_thread);
	}

	for(SocketSetIt it = m_socket_set.begin();
		it != m_socket_set.end(); ++it)
	{
		NetSocket *p = *it;
		SAFE_DELETE(p);
	}
	m_socket_set.clear();
}

void NetApp::RunProc()
{
	boost::system::error_code error;
	m_io_service.run(error);
	if(error)
	{
		LOG_ERROR("%s, io_service run failed", __FUNCTION__);
	}
}